<?php
include_once 'application/controllers/AbstractController.php';
require_once 'application/models/Utilisateur.php';

class UtilisateurController extends AbstractController
{
	function init()
	{
		// init
	}
	

	function loginAction()
	{
	}

	function indexAction()
    {
		parent::indexAction();
    	HttpUtil::do405();
    }
    
    
    function getAction()
    {
		parent::getAction();
    	HttpUtil::do405();
    }
    
    function postAction()
    {
		parent::postAction();
    	// collect the data from the user
		Zend_Loader::loadClass('Zend_Filter_StripTags');
		$f = new Zend_Filter_StripTags();
		$mail = $f->filter($this->_request->getParam('email'));
		$login = $mail;
		$name = $f->filter($this->_request->getParam('name'));
		$password = $f->filter($this->_request->getParam('password'));

		$isValid = TypeChecker::validate(array(
			array('data' => $mail, 'type' => TypeChecker::$_EMAIL_TYPE, 'name' => 'mail'),
			array('data' => $name, 'type' => TypeChecker::$_TEXT_TYPE, 'name' => 'name'),
			array('data' => $password, 'type' => TypeChecker::$_TEXT_TYPE, 'name' => 'password')
		));
		if ($isValid !== true) {
			HttpUtil::do400('validation', $isValid);
		}
		
		$table = new Utilisateur();

		$where = $table->getAdapter()->quoteInto('login = ?', $login);
	    $userRows = $table->fetchAll($where);
		if (isset($userRows[0])) {
			HttpUtil::do400('login_exists');
		}
				
		// insert the new user
		try {
			$data = array(
				'login' => $login,
				'email' => $mail,
				'firstname' => $name,
				'lastname' => $name,
				'digest_password' => sha1($password . Zend_Registry::getInstance()->get('config')->salt)
			);
			$lastInsertId = $table->insert($data);  
		}catch(Exception $exception) {
			print_r($exception);
			HttpUtil::do400('creation_failed');
		}
	    
		// log in !
		
		// setup Zend_Auth adapter for a database table
		Zend_Loader::loadClass('Zend_Auth_Adapter_DbTable');
		$dbAdapter = Zend_Registry::get('dbAdapter');
		$authAdapter = new Zend_Auth_Adapter_DbTable($dbAdapter);
		$authAdapter->setTableName('Utilisateur');
		$authAdapter->setIdentityColumn('login');
		$authAdapter->setCredentialColumn('digest_password');

		// Set the input credential values to authenticate against
		$authAdapter->setIdentity($login);
		$authAdapter->setCredential(sha1($password . Zend_Registry::getInstance()->get('config')->salt));

		// do the authentication
		$auth = Zend_Auth::getInstance();
		$result = $auth->authenticate($authAdapter);

		
		//if valid member found, store the information in session memory.
		if ($result->isValid()) {
			$data = $authAdapter->getResultRowObject(null, 'password');
			$auth->getStorage()->write($data);
			$userdata = $auth->getIdentity();
			if($userdata->status == 0){
				$auth->clearIdentity();
				HttpUtil::do401('desactivated_account');
				$inactive = 'True';
			}
		} else {
			// failure: clear database row from session
			HttpUtil::do401();
		}
				
		HttpUtil::set201();
		
		//TODO:log !
    }
    
    function putAction()
    {
		parent::putAction();
		$newUser;
    	//TODO: check rights pour chaque fonction
		//TODO: modification_date (pour le cache surtout -> faire un hash et comparer)
		
		// get params
		$charSize = $this->getRequest()->getParam('charSize');
		$displayTime = $this->getRequest()->getParam('displayTime');
		$inverse = $this->getRequest()->getParam('inverse');
		$dictee = $this->getRequest()->getParam('dictee');
		$feedback = $this->getRequest()->getParam('feedback');
		$assist = $this->getRequest()->getParam('assist');
		$tempo = $this->getRequest()->getParam('tempo');
		
		// check params type
		$isValid = TypeChecker::validate(array(
			array('data' => $charSize, 'type' => TypeChecker::$_NUM_TYPE, 'name' => 'charSize'),
			array('data' => $displayTime, 'type' => TypeChecker::$_TEXT_TYPE, 'name' => 'displayTime'),
			array('data' => $inverse, 'type' => TypeChecker::$_TEXT_TYPE, 'name' => 'inverse'),
			array('data' => $dictee, 'type' => TypeChecker::$_TEXT_TYPE, 'name' => 'dictee'),
			array('data' => $feedback, 'type' => TypeChecker::$_TEXT_TYPE, 'name' => 'feedback'),
			array('data' => $assist, 'type' => TypeChecker::$_TEXT_TYPE, 'name' => 'assist'),
			array('data' => $tempo, 'type' => TypeChecker::$_TEXT_TYPE, 'name' => 'tempo')
		));
		if ($isValid !== true) {
			HttpUtil::do400('validation', $isValid);
		}
   		
		try {
			$table = new Utilisateur();
			 
			// update table
			$data = array(
				'default_char_size'=> $charSize,
				'default_display_time'=> $displayTime,
				'default_inverse'=> $inverse,
				'default_dictee'=> $dictee,
				'default_feedback'=> $feedback,
				'default_assist'=> $assist,
				'default_tempo'=> $tempo
			);
			
			$where = $table->getAdapter()->quoteInto('id = ?', $this->user->id);
			$numberOfRows = $table->update($data, $where);
			
			// get new user
			$table = new Utilisateur();
			$where = $table->getAdapter()->quoteInto('id = ?', $this->user->id);
		    $userRows = $table->fetchAll($where);
			if (!isset($userRows[0])) {
				HttpUtil::do400('update_failed');
			}
			$newUser = $userRows[0];
		}catch(Exception $exception) {
			HttpUtil::do400('update_failed');
		}

		Zend_Auth::getInstance()->getStorage()->write($newUser);
		$this->view->data = json_encode($table->getArrayFromRow($newUser), JSON_FORCE_OBJECT);
    }
    
    function deleteAction()
    {
		parent::deleteAction();
    	HttpUtil::do405();
    }
		
}